package com.cxc.simple;

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class FileDownLoad {

   private static final int THREAD_COUNT = 2;
   private static final String FILE_URL="https://example.com/file.zip";
   private static final String OUTPUT_FILE = "file.zip";

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(THREAD_COUNT);

        try {
            HttpURLConnection connection = (HttpURLConnection) new URL(FILE_URL).openConnection();
            int fileSize = connection.getContentLength();
            connection.disconnect();

            int chunkSize = fileSize / THREAD_COUNT;
            for (int i = 0; i < THREAD_COUNT; i++) {
                int start = i * chunkSize;
                int end = (i == THREAD_COUNT - 1) ? fileSize : start + chunkSize - 1;
                executorService.execute(new DownloadTask(start, end));
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally  {
            executorService.shutdown();
        }
    };


    static class DownloadTask implements Runnable {
        private int start;
        private int end;

        public DownloadTask(int start, int end) {
            this.start = start;
            this.end = end;
        }

        @Override
        public void run() {
            try {
                HttpURLConnection connection = (HttpURLConnection) new URL(FILE_URL).openConnection();
                connection.setRequestProperty("Range", "bytes=" + start + "-" + end);
                BufferedInputStream inputStream = new BufferedInputStream(connection.getInputStream());
                FileOutputStream outputStream = new FileOutputStream(OUTPUT_FILE, true);

                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }

                inputStream.close();
                outputStream.close();
                connection.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
